<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>番茄时钟 - 专注力助手</title>
    <style>
        /* CSS变量系统 */
        :root {
            /* 颜色主题 */
            --work-bg-primary: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            --work-bg-secondary: rgba(102, 126, 234, 0.1);
            --rest-bg-primary: linear-gradient(135deg, #2d5016 0%, #3a6b35 100%);
            --rest-bg-secondary: rgba(45, 80, 22, 0.1);
            --long-rest-bg-primary: linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%);
            --long-rest-bg-secondary: rgba(255, 154, 158, 0.1);

            /* 字体颜色 */
            --text-primary: #2d3748;
            --text-secondary: #4a5568;
            --text-light: #718096;
            --text-white: #ffffff;

            /* 间距 */
            --spacing-xs: 0.5rem;
            --spacing-sm: 1rem;
            --spacing-md: 1.5rem;
            --spacing-lg: 2rem;
            --spacing-xl: 3rem;

            /* 动画时长 */
            --transition-fast: 0.3s;
            --transition-medium: 0.5s;
            --transition-slow: 1s;

            /* 字体大小 */
            --font-size-xs: 0.875rem;
            --font-size-sm: 1rem;
            --font-size-md: 1.25rem;
            --font-size-lg: 1.5rem;
            --font-size-xl: 2rem;
            --font-size-xxl: 3rem;
            --font-size-xxxl: 4rem;

            /* 边框圆角 */
            --border-radius-sm: 0.5rem;
            --border-radius-md: 1rem;
            --border-radius-lg: 1.5rem;
            --border-radius-xl: 2rem;

            /* 阴影 */
            --shadow-sm: 0 1px 3px rgba(0, 0, 0, 0.12), 0 1px 2px rgba(0, 0, 0, 0.24);
            --shadow-md: 0 4px 6px rgba(0, 0, 0, 0.1), 0 2px 4px rgba(0, 0, 0, 0.06);
            --shadow-lg: 0 10px 25px rgba(0, 0, 0, 0.15), 0 6px 10px rgba(0, 0, 0, 0.08);
        }

        /* 全局样式重置 */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: var(--work-bg-primary);
            color: var(--text-white);
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            transition: background var(--transition-slow) ease;
            overflow: hidden;
            position: relative;
        }

        /* 背景动画效果 */
        body::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: radial-gradient(circle at 20% 80%, transparent 50%, rgba(255, 255, 255, 0.1) 51%);
            animation: float 6s ease-in-out infinite;
        }

        @keyframes float {
            0%, 100% { transform: translateY(0px) rotate(0deg); }
            50% { transform: translateY(-20px) rotate(1deg); }
        }

        /* 状态类 */
        body.rest-mode {
            background: var(--rest-bg-primary);
        }

        body.long-rest-mode {
            background: var(--long-rest-bg-primary);
        }

        /* 主容器 */
        .container {
            width: 100%;
            max-width: 600px;
            padding: var(--spacing-lg);
            text-align: center;
            position: relative;
            z-index: 1;
        }

        /* 时间显示区域 */
        .timer-display {
            margin-bottom: var(--spacing-xl);
            animation: fadeInUp 1s ease-out;
        }

        .time-text {
            font-size: var(--font-size-xxxl);
            font-weight: 300;
            margin-bottom: var(--spacing-md);
            text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
            letter-spacing: 0.05em;
            font-variant-numeric: tabular-nums;
        }

        .mode-indicator {
            font-size: var(--font-size-lg);
            font-weight: 500;
            margin-bottom: var(--spacing-md);
            opacity: 0.9;
            text-transform: uppercase;
            letter-spacing: 0.1em;
        }

        /* 循环计数器 */
        .cycle-counter {
            background: rgba(255, 255, 255, 0.2);
            border-radius: var(--border-radius-lg);
            padding: var(--spacing-sm) var(--spacing-md);
            margin-bottom: var(--spacing-lg);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255, 255, 255, 0.3);
            font-size: var(--font-size-sm);
        }

        .cycle-count {
            font-weight: 600;
            color: var(--text-white);
        }

        /* 激励文本区域 */
        .motivation-section {
            margin-bottom: var(--spacing-xl);
            min-height: 80px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .motivation-text {
            font-size: var(--font-size-md);
            line-height: 1.6;
            font-style: italic;
            opacity: 0.95;
            max-width: 500px;
            margin: 0 auto;
            text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.3);
            animation: fadeIn 2s ease-out;
        }

        /* 控制按钮区域 */
        .controls {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: var(--spacing-md);
            margin-bottom: var(--spacing-lg);
            max-width: 500px;
            margin-left: auto;
            margin-right: auto;
        }

        .btn {
            padding: var(--spacing-md) var(--spacing-lg);
            border: none;
            border-radius: var(--border-radius-md);
            font-size: var(--font-size-sm);
            font-weight: 600;
            cursor: pointer;
            transition: all var(--transition-fast) ease;
            text-transform: uppercase;
            letter-spacing: 0.05em;
            position: relative;
            overflow: hidden;
            backdrop-filter: blur(5px);
            border: 2px solid rgba(255, 255, 255, 0.3);
            background: rgba(255, 255, 255, 0.1);
            color: var(--text-white);
        }

        .btn::before {
            content: '';
            position: absolute;
            top: 50%;
            left: 50%;
            width: 0;
            height: 0;
            background: rgba(255, 255, 255, 0.3);
            border-radius: 50%;
            transform: translate(-50%, -50%);
            transition: width var(--transition-fast), height var(--transition-fast);
        }

        .btn:hover::before {
            width: 300px;
            height: 300px;
        }

        .btn:hover {
            transform: translateY(-2px);
            box-shadow: var(--shadow-lg);
            background: rgba(255, 255, 255, 0.2);
        }

        .btn:active {
            transform: translateY(0);
        }

        .btn-primary {
            background: rgba(255, 255, 255, 0.25);
            border-color: rgba(255, 255, 255, 0.4);
        }

        .btn-secondary {
            background: rgba(255, 255, 255, 0.15);
            border-color: rgba(255, 255, 255, 0.3);
        }

        .btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
            transform: none;
        }

        /* 提示消息 */
        .notification {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%) scale(0);
            background: rgba(255, 255, 255, 0.95);
            color: var(--text-primary);
            padding: var(--spacing-xl);
            border-radius: var(--border-radius-xl);
            box-shadow: var(--shadow-lg);
            z-index: 1000;
            text-align: center;
            max-width: 400px;
            opacity: 0;
            transition: all var(--transition-medium) cubic-bezier(0.68, -0.55, 0.265, 1.55);
        }

        .notification.show {
            transform: translate(-50%, -50%) scale(1);
            opacity: 1;
        }

        .notification h3 {
            margin-bottom: var(--spacing-sm);
            font-size: var(--font-size-lg);
            color: var(--text-primary);
        }

        .notification p {
            font-size: var(--font-size-sm);
            color: var(--text-secondary);
            line-height: 1.5;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .container {
                padding: var(--spacing-md);
            }

            .time-text {
                font-size: var(--font-size-xxl);
            }

            .controls {
                grid-template-columns: repeat(2, 1fr);
                max-width: 400px;
            }

            .reset-count-section {
                margin-top: var(--spacing-sm);
            }

            .motivation-text {
                font-size: var(--font-size-sm);
                padding: 0 var(--spacing-sm);
            }
        }

        @media (max-width: 480px) {
            .time-text {
                font-size: var(--font-size-xl);
            }

            .controls {
                grid-template-columns: repeat(2, 1fr);
                max-width: 300px;
                gap: var(--spacing-sm);
            }

            .reset-count-section {
                margin-top: var(--spacing-xs);
            }

            .reset-count-btn {
                min-width: 120px;
                font-size: var(--font-size-xs);
            }

            .btn {
                padding: var(--spacing-sm) var(--spacing-md);
                font-size: var(--font-size-xs);
            }
        }

        /* 动画 */
        @keyframes fadeInUp {
            from {
                opacity: 0;
                transform: translateY(30px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }

        @keyframes pulse {
            0%, 100% { transform: scale(1); }
            50% { transform: scale(1.05); }
        }

        .pulse {
            animation: pulse 2s ease-in-out infinite;
        }

        /* 设置面板 */
        .settings-panel {
            position: fixed;
            top: var(--spacing-sm);
            right: var(--spacing-sm);
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(10px);
            border-radius: var(--border-radius-md);
            padding: var(--spacing-sm);
            border: 1px solid rgba(255, 255, 255, 0.2);
            z-index: 100;
        }

        .settings-btn {
            background: none;
            border: none;
            color: var(--text-white);
            font-size: var(--font-size-lg);
            cursor: pointer;
            padding: var(--spacing-xs);
            border-radius: var(--border-radius-sm);
            transition: background var(--transition-fast);
        }

        .settings-btn:hover {
            background: rgba(255, 255, 255, 0.2);
        }

        /* 设置模态框 */
        .settings-modal {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.7);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 2000;
            opacity: 0;
            visibility: hidden;
            transition: all var(--transition-medium) ease;
        }

        .settings-modal.show {
            opacity: 1;
            visibility: visible;
        }

        .settings-content {
            background: var(--work-bg-primary);
            border-radius: var(--border-radius-xl);
            padding: var(--spacing-xl);
            max-width: 500px;
            width: 90%;
            max-height: 80vh;
            overflow-y: auto;
            transform: scale(0.9);
            transition: transform var(--transition-medium) ease;
        }

        .settings-modal.show .settings-content {
            transform: scale(1);
        }

        .settings-header {
            text-align: center;
            margin-bottom: var(--spacing-lg);
        }

        .settings-title {
            font-size: var(--font-size-xl);
            margin-bottom: var(--spacing-sm);
        }

        .settings-group {
            background: rgba(255, 255, 255, 0.1);
            border-radius: var(--border-radius-md);
            padding: var(--spacing-md);
            margin-bottom: var(--spacing-md);
        }

        .settings-group-title {
            font-size: var(--font-size-md);
            margin-bottom: var(--spacing-md);
            font-weight: 600;
            border-bottom: 1px solid rgba(255, 255, 255, 0.2);
            padding-bottom: var(--spacing-sm);
        }

        .settings-item {
            margin-bottom: var(--spacing-md);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .settings-label {
            font-size: var(--font-size-sm);
            flex: 1;
        }

        .settings-control {
            display: flex;
            align-items: center;
            gap: var(--spacing-sm);
        }

        .settings-input {
            background: rgba(255, 255, 255, 0.2);
            border: 1px solid rgba(255, 255, 255, 0.3);
            border-radius: var(--border-radius-sm);
            padding: var(--spacing-xs) var(--spacing-sm);
            color: var(--text-white);
            font-size: var(--font-size-sm);
            width: 80px;
            text-align: center;
        }

        .settings-input:focus {
            outline: none;
            border-color: rgba(255, 255, 255, 0.5);
            background: rgba(255, 255, 255, 0.3);
        }

        .settings-checkbox {
            width: 20px;
            height: 20px;
            cursor: pointer;
        }

        .settings-select {
            background: rgba(255, 255, 255, 0.2);
            border: 1px solid rgba(255, 255, 255, 0.3);
            border-radius: var(--border-radius-sm);
            padding: var(--spacing-xs) var(--spacing-sm);
            color: var(--text-white);
            font-size: var(--font-size-sm);
            cursor: pointer;
        }

        .settings-select:focus {
            outline: none;
            border-color: rgba(255, 255, 255, 0.5);
        }

        .settings-select option {
            background: #2d3748;
            color: var(--text-white);
            padding: var(--spacing-xs);
        }

        .settings-actions {
            display: flex;
            justify-content: center;
            gap: var(--spacing-md);
            margin-top: var(--spacing-lg);
        }

        .settings-btn-action {
            padding: var(--spacing-sm) var(--spacing-lg);
            border: 2px solid rgba(255, 255, 255, 0.3);
            border-radius: var(--border-radius-md);
            background: rgba(255, 255, 255, 0.1);
            color: var(--text-white);
            font-size: var(--font-size-sm);
            cursor: pointer;
            transition: all var(--transition-fast);
        }

        .settings-btn-action:hover {
            background: rgba(255, 255, 255, 0.2);
            transform: translateY(-1px);
        }

        .settings-btn-primary {
            background: rgba(255, 255, 255, 0.25);
            border-color: rgba(255, 255, 255, 0.4);
        }

        .settings-btn-danger {
            background: rgba(239, 68, 68, 0.2);
            border-color: rgba(239, 68, 68, 0.4);
        }

        /* 历史记录模态框 */
        .history-modal {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.8);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 2000;
            opacity: 0;
            visibility: hidden;
            transition: all var(--transition-medium) ease;
        }

        .history-modal.show {
            opacity: 1;
            visibility: visible;
        }

        .history-content {
            background: #2d3748;
            border-radius: var(--border-radius-xl);
            padding: var(--spacing-xl);
            max-width: 600px;
            width: 90%;
            max-height: 80vh;
            overflow-y: auto;
            transform: scale(0.9);
            transition: transform var(--transition-medium) ease;
        }

        .history-modal.show .history-content {
            transform: scale(1);
        }

        .history-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: var(--spacing-lg);
        }

        .history-title {
            font-size: var(--font-size-xl);
            color: var(--text-white);
            margin: 0;
        }

        .history-close-btn {
            background: none;
            border: none;
            color: var(--text-white);
            font-size: var(--font-size-lg);
            cursor: pointer;
            padding: var(--spacing-xs);
            border-radius: var(--border-radius-sm);
            transition: background var(--transition-fast);
        }

        .history-close-btn:hover {
            background: rgba(255, 255, 255, 0.1);
        }

        .history-stats {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: var(--spacing-md);
            margin-bottom: var(--spacing-lg);
        }

        .stat-card {
            background: rgba(255, 255, 255, 0.1);
            border-radius: var(--border-radius-md);
            padding: var(--spacing-md);
            text-align: center;
        }

        .stat-number {
            font-size: var(--font-size-xl);
            font-weight: 600;
            color: var(--text-white);
            margin-bottom: var(--spacing-xs);
        }

        .stat-label {
            font-size: var(--font-size-sm);
            color: rgba(255, 255, 255, 0.7);
        }

        .history-list {
            max-height: 300px;
            overflow-y: auto;
        }

        .history-item {
            background: rgba(255, 255, 255, 0.05);
            border-radius: var(--border-radius-sm);
            padding: var(--spacing-md);
            margin-bottom: var(--spacing-sm);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .history-date {
            color: var(--text-white);
            font-weight: 500;
        }

        .history-count {
            color: var(--text-white);
            font-weight: 600;
        }

        .history-empty {
            text-align: center;
            color: rgba(255, 255, 255, 0.6);
            padding: var(--spacing-xl);
            font-size: var(--font-size-md);
        }

        /* 重置计数按钮样式 */
        .reset-count-section {
            display: flex;
            justify-content: center;
            margin-top: var(--spacing-md);
        }

        .reset-count-btn {
            min-width: 150px;
            font-size: var(--font-size-sm);
            background: rgba(255, 255, 255, 0.15);
            border-color: rgba(255, 255, 255, 0.25);
        }

        .reset-count-btn:hover {
            background: rgba(255, 255, 255, 0.25);
            transform: translateY(-2px);
        }
    </style>
</head>
<body>
    <!-- 设置面板 -->
    <div class="settings-panel">
        <button class="settings-btn" onclick="openSettings()" title="设置">
            ⚙️
        </button>
    </div>

    <!-- 设置模态框 -->
    <div class="settings-modal" id="settingsModal">
        <div class="settings-content">
            <div class="settings-header">
                <h2 class="settings-title">⚙️ 设置</h2>
                <p style="color: var(--text-white); opacity: 0.8;">自定义您的番茄时钟体验</p>
            </div>

            <!-- 时间设置 -->
            <div class="settings-group">
                <div class="settings-group-title">⏰ 时间设置</div>

                <div class="settings-item">
                    <label class="settings-label">工作时间（分钟）</label>
                    <div class="settings-control">
                        <input type="number" class="settings-input" id="workTimeInput" min="1" max="60" value="25">
                        <span style="color: var(--text-white); opacity: 0.7;">分钟</span>
                    </div>
                </div>

                <div class="settings-item">
                    <label class="settings-label">短休息时间（分钟）</label>
                    <div class="settings-control">
                        <input type="number" class="settings-input" id="restTimeInput" min="1" max="30" value="5">
                        <span style="color: var(--text-white); opacity: 0.7;">分钟</span>
                    </div>
                </div>

                <div class="settings-item">
                    <label class="settings-label">长休息时间（分钟）</label>
                    <div class="settings-control">
                        <input type="number" class="settings-input" id="longRestTimeInput" min="1" max="60" value="15">
                        <span style="color: var(--text-white); opacity: 0.7;">分钟</span>
                    </div>
                </div>

                <div class="settings-item">
                    <label class="settings-label">长休息间隔（几个番茄钟）</label>
                    <div class="settings-control">
                        <input type="number" class="settings-input" id="longRestIntervalInput" min="2" max="10" value="4">
                        <span style="color: var(--text-white); opacity: 0.7;">个</span>
                    </div>
                </div>
            </div>

            <!-- 提醒设置 -->
            <div class="settings-group">
                <div class="settings-group-title">🔔 提醒设置</div>

                <div class="settings-item">
                    <label class="settings-label">启用音频提醒</label>
                    <div class="settings-control">
                        <input type="checkbox" class="settings-checkbox" id="audioEnabledInput" checked>
                    </div>
                </div>

                <div class="settings-item">
                    <label class="settings-label">启用桌面通知</label>
                    <div class="settings-control">
                        <input type="checkbox" class="settings-checkbox" id="notificationEnabledInput" checked>
                    </div>
                </div>

                <div class="settings-item">
                    <label class="settings-label">音量大小</label>
                    <div class="settings-control">
                        <select class="settings-select" id="volumeLevelInput">
                            <option value="quiet">安静</option>
                            <option value="normal" selected>正常</option>
                            <option value="loud">响亮</option>
                        </select>
                    </div>
                </div>
            </div>

            <!-- 显示设置 -->
            <div class="settings-group">
                <div class="settings-group-title">🎨 显示设置</div>

                <div class="settings-item">
                    <label class="settings-label">背景动画效果</label>
                    <div class="settings-control">
                        <input type="checkbox" class="settings-checkbox" id="bgAnimationEnabledInput" checked>
                    </div>
                </div>

                <div class="settings-item">
                    <label class="settings-label">显示循环计数</label>
                    <div class="settings-control">
                        <input type="checkbox" class="settings-checkbox" id="showCycleCountInput" checked>
                    </div>
                </div>
            </div>

            <!-- 数据管理 -->
            <div class="settings-group">
                <div class="settings-group-title">📊 数据管理</div>

                <div class="settings-item">
                    <label class="settings-label">每日自动重置计数</label>
                    <div class="settings-control">
                        <input type="checkbox" class="settings-checkbox" id="autoResetDailyInput" checked>
                    </div>
                </div>

                <div class="settings-item">
                    <label class="settings-label">今日完成番茄钟</label>
                    <div class="settings-control">
                        <span id="todayStats" style="color: var(--text-white); font-weight: 600;">0</span>
                    </div>
                </div>

                <div class="settings-item">
                    <label class="settings-label">历史记录查看</label>
                    <div class="settings-control">
                        <button class="settings-btn-action" onclick="showHistory()" style="padding: var(--spacing-xs) var(--spacing-sm); font-size: var(--font-size-xs);">
                            📊 查看历史
                        </button>
                    </div>
                </div>
            </div>

            <!-- 操作按钮 -->
            <div class="settings-actions">
                <button class="settings-btn-action settings-btn-primary" onclick="saveSettings()">
                    保存设置
                </button>
                <button class="settings-btn-action" onclick="closeSettings()">
                    取消
                </button>
                <button class="settings-btn-action settings-btn-danger" onclick="resetAllData()">
                    重置所有数据
                </button>
            </div>
        </div>
    </div>

    <!-- 历史记录模态框 -->
    <div class="history-modal" id="historyModal">
        <div class="history-content">
            <div class="history-header">
                <h2 class="history-title">📊 历史记录</h2>
                <button class="history-close-btn" onclick="closeHistory()">✕</button>
            </div>
            <div class="history-body">
                <div class="history-stats">
                    <div class="stat-card">
                        <div class="stat-number" id="totalPomodoros">0</div>
                        <div class="stat-label">总计完成</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-number" id="currentStreak">0</div>
                        <div class="stat-label">连续天数</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-number" id="avgPomodoros">0</div>
                        <div class="stat-label">日均完成</div>
                    </div>
                </div>
                <div class="history-list" id="historyList">
                    <!-- 历史记录将在这里显示 -->
                </div>
            </div>
        </div>
    </div>

    <!-- 主容器 -->
    <div class="container">
        <!-- 时间显示 -->
        <div class="timer-display">
            <div class="mode-indicator" id="modeIndicator">工作时间</div>
            <div class="time-text" id="timeDisplay">25:00</div>
        </div>

        <!-- 循环计数 -->
        <div class="cycle-counter">
            <span>第 <span class="cycle-count" id="cycleCount">0</span> 个番茄钟</span>
        </div>

        <!-- 激励文本 -->
        <div class="motivation-section">
            <div class="motivation-text" id="motivationText">
                准备开始专注工作，让每一分钟都有价值！
            </div>
        </div>

        <!-- 控制按钮 -->
        <div class="controls">
            <button class="btn btn-primary" id="startBtn" onclick="startTimer()">
                开始
            </button>
            <button class="btn btn-secondary" id="pauseBtn" onclick="pauseTimer()" disabled>
                暂停
            </button>
            <button class="btn btn-secondary" id="skipBtn" onclick="skipTimer()">
                跳过
            </button>
            <button class="btn btn-secondary" id="resetBtn" onclick="resetTimer()">
                重新开始
            </button>
        </div>

        <!-- 重置计数按钮 -->
        <div class="reset-count-section">
            <button class="btn btn-secondary reset-count-btn" onclick="resetCycleCount()">
                🔄 重置计数
            </button>
        </div>
    </div>

    <!-- 提示消息 -->
    <div class="notification" id="notification">
        <h3 id="notificationTitle">提醒</h3>
        <p id="notificationMessage">消息内容</p>
    </div>

    <script>
        // ============ 全局变量 ============
        let timer = null;
        let remainingSeconds = 25 * 60; // 默认25分钟
        let isRunning = false;
        let isPaused = false;
        let currentMode = 'work'; // 'work', 'rest', 'long-rest'
        let cycleCount = 1; // 从1开始计数
        let audioContext = null;

        // ============ 配置常量 ============
        let CONFIG = {
            WORK_TIME: 25 * 60,      // 25分钟工作时间（秒）
            REST_TIME: 5 * 60,       // 5分钟休息时间（秒）
            LONG_REST_TIME: 15 * 60, // 15分钟长休息时间（秒）
            CYCLES_PER_LONG_REST: 4, // 每4个循环后长休息

            // 音频和通知设置
            audioEnabled: true,
            notificationEnabled: true,
            volumeLevel: 'normal',

            // 显示设置
            bgAnimationEnabled: true,
            showCycleCount: true,

            // 数据管理
            autoResetDaily: true,

            // 工作时间激励语
            workMotivations: [
                "专注当下，成就未来！",
                "每一分钟的专注，都是对梦想的投资。",
                "深度工作，创造非凡价值。",
                "现在的努力，是未来最好的礼物。",
                "专注力是成功的第一要素。",
                "时间就是生命，珍惜每一秒。",
                "高效的专注，胜过漫长的时间。",
                "心无旁骛，方能致远。",
                "今天的专注，明天的成就。",
                "深度思考，让工作更有意义。",
                "屏蔽干扰，释放潜能。",
                "专注创造价值，时间见证成长。"
            ],

            // 休息时间建议
            restSuggestions: [
                "起来走动一下，伸展身体。",
                "喝杯水，补充水分。",
                "做几个简单的眼部运动。",
                "远眺窗外，放松眼睛。",
                "深呼吸，让大脑放松。",
                "扭扭腰，活动一下肩膀。",
                "听听轻松的音乐。",
                "吃点健康的小零食。",
                "整理一下桌面环境。",
                "和朋友聊聊天，放松心情。",
                "做几个简单的拉伸动作。",
                "闭目养神，让大脑休息。"
            ]
        };

        // ============ 音频管理 ============
        class AudioManager {
            constructor() {
                this.context = null;
                this.initialized = false;
                this.isPlaying = false;
            }

            async init() {
                if (this.initialized) return;

                try {
                    this.context = new (window.AudioContext || window.webkitAudioContext)();
                    this.initialized = true;
                } catch (error) {
                    console.log('音频API不可用:', error);
                }
            }

            playGentleNotification(type = 'work') {
                if (!this.initialized || this.isPlaying) return;

                this.isPlaying = true;
                const now = this.context.currentTime;

                // 创建振荡器（音调生成器）
                const oscillator1 = this.context.createOscillator();
                const oscillator2 = this.context.createOscillator();

                // 创建增益节点（音量控制）
                const gainNode = this.context.createGain();

                // 设置波形类型（正弦波最温柔）
                oscillator1.type = 'sine';
                oscillator2.type = 'sine';

                // 根据类型设置不同的音调
                if (type === 'work') {
                    // 工作结束：较高音调，提醒但不刺耳
                    oscillator1.frequency.setValueAtTime(800, now);
                    oscillator2.frequency.setValueAtTime(1000, now);
                } else {
                    // 休息结束：较低音调，温柔唤醒
                    oscillator1.frequency.setValueAtTime(600, now);
                    oscillator2.frequency.setValueAtTime(750, now);
                }

                // 设置音量包络（淡入淡出效果）
                gainNode.gain.setValueAtTime(0, now);
                gainNode.gain.linearRampToValueAtTime(0.3, now + 0.1);  // 快速淡入
                gainNode.gain.exponentialRampToValueAtTime(0.01, now + 1.5);  // 缓慢淡出

                // 连接音频节点
                oscillator1.connect(gainNode);
                oscillator2.connect(gainNode);
                gainNode.connect(this.context.destination);

                // 开始和停止播放
                oscillator1.start(now);
                oscillator2.start(now);

                // 自动清理和重置状态
                const stopTime = now + 1.5;
                oscillator1.stop(stopTime);
                oscillator2.stop(stopTime);

                setTimeout(() => {
                    this.isPlaying = false;
                }, 1500);
            }

            // 清理资源
            cleanup() {
                if (this.context && this.context.state !== 'closed') {
                    this.context.close();
                }
                this.initialized = false;
                this.isPlaying = false;
            }
        }

        const audioManager = new AudioManager();

        // ============ DOM缓存优化 ============
        const DOMCache = {
            timeDisplay: document.getElementById('timeDisplay'),
            modeIndicator: document.getElementById('modeIndicator'),
            motivationText: document.getElementById('motivationText'),
            cycleCount: document.getElementById('cycleCount'),
            startBtn: document.getElementById('startBtn'),
            pauseBtn: document.getElementById('pauseBtn'),
            resetBtn: document.getElementById('resetBtn'),
            skipBtn: document.getElementById('skipBtn'),
            notification: document.getElementById('notification'),
            notificationTitle: document.getElementById('notificationTitle'),
            notificationMessage: document.getElementById('notificationMessage')
        };

        // ============ 性能优化的工具函数 ============
        function formatTime(seconds) {
            const minutes = Math.floor(seconds / 60);
            const remainingSecs = seconds % 60;
            return `${minutes.toString().padStart(2, '0')}:${remainingSecs.toString().padStart(2, '0')}`;
        }

        function getRandomElement(array) {
            return array[Math.floor(Math.random() * array.length)];
        }

        // 批量更新DOM，减少重绘
        function batchDOMUpdate(updates) {
            requestAnimationFrame(() => {
                updates.forEach(update => update());
            });
        }

        function updateDisplay(updateMotivation = true) {
            // 使用缓存的DOM元素和批量更新优化
            batchDOMUpdate([
                () => DOMCache.timeDisplay.textContent = formatTime(remainingSeconds),
                () => DOMCache.cycleCount.textContent = cycleCount
            ]);

            // 更新模式和背景
            const updates = [];

            if (currentMode === 'work') {
                updates.push(() => DOMCache.modeIndicator.textContent = '工作时间');
                document.body.className = '';
                if (updateMotivation) {
                    updates.push(() => DOMCache.motivationText.textContent = getRandomElement(CONFIG.workMotivations));
                }
            } else if (currentMode === 'rest') {
                updates.push(() => DOMCache.modeIndicator.textContent = '休息时间');
                document.body.className = 'rest-mode';
                if (updateMotivation) {
                    updates.push(() => DOMCache.motivationText.textContent = getRandomElement(CONFIG.restSuggestions));
                }
            } else if (currentMode === 'long-rest') {
                updates.push(() => DOMCache.modeIndicator.textContent = '长休息时间');
                document.body.className = 'long-rest-mode';
                if (updateMotivation) {
                    updates.push(() => DOMCache.motivationText.textContent = '恭喜完成4个番茄钟！享受这个长休息时间，好好放松一下。');
                }
            }

            batchDOMUpdate(updates);
        }

        function showNotification(title, message, duration = 3000) {
            // 使用缓存DOM元素
            batchDOMUpdate([
                () => DOMCache.notificationTitle.textContent = title,
                () => DOMCache.notificationMessage.textContent = message
            ]);

            DOMCache.notification.classList.add('show');

            setTimeout(() => {
                DOMCache.notification.classList.remove('show');
            }, duration);
        }

        function requestNotificationPermission() {
            if ('Notification' in window && Notification.permission === 'default') {
                Notification.requestPermission().then(permission => {
                    if (permission === 'granted') {
                        console.log('桌面通知权限已获得');
                    }
                });
            }
        }

        function sendDesktopNotification(title, body) {
            if ('Notification' in window && Notification.permission === 'granted') {
                new Notification(title, {
                    body: body,
                    icon: 'data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><text y=".9em" font-size="90">🍅</text></svg>'
                });
            }
        }

        // ============ 计时器核心功能 ============
        function startTimer() {
            if (!isRunning) {
                // 如果时间已经到了（remainingSeconds为0），则切换到下一个模式
                if (remainingSeconds === 0) {
                    // 直接调用switchMode，它会处理计数逻辑
                    switchMode();
                    return; // 提前返回，避免重复执行
                }

                isRunning = true;
                isPaused = false;

                // 初始化音频（用户交互后才能播放）
                audioManager.init();

                DOMCache.startBtn.disabled = true;
                DOMCache.pauseBtn.disabled = false;

                timer = setInterval(() => {
                    if (remainingSeconds > 0) {
                        remainingSeconds--;
                        updateDisplay(false); // 不更新激励内容
                    } else {
                        // 时间到了，停止计时并显示模式切换通知
                        clearInterval(timer);
                        timer = null;
                        isRunning = false;
                        isPaused = false;

                        // 重置按钮状态
                        DOMCache.startBtn.disabled = false;
                        DOMCache.startBtn.textContent = '开始';
                        DOMCache.pauseBtn.disabled = true;

                        // 显示模式切换通知，但不自动切换
                        showModeSwitchNotification();
                    }
                }, 1000);
            }
        }

        function pauseTimer() {
            if (isRunning && !isPaused) {
                isPaused = true;
                isRunning = false;
                clearInterval(timer);

                DOMCache.startBtn.disabled = false;
                DOMCache.startBtn.textContent = '继续';
                DOMCache.pauseBtn.disabled = true;
            }
        }

        function resetTimer() {
            clearInterval(timer);
            timer = null;
            isRunning = false;
            isPaused = false;
            remainingSeconds = CONFIG.WORK_TIME;
            currentMode = 'work';

            DOMCache.startBtn.disabled = false;
            DOMCache.startBtn.textContent = '开始';
            DOMCache.pauseBtn.disabled = true;

            updateDisplay();
        }

        function skipTimer() {
            clearInterval(timer);
            timer = null;
            isRunning = false;
            isPaused = false;

            DOMCache.startBtn.disabled = false;
            DOMCache.startBtn.textContent = '开始';
            DOMCache.pauseBtn.disabled = true;

            switchMode();
        }

        /**
         * 切换番茄钟模式
         * 工作完成 -> 休息/长休息
         * 休息完成 -> 工作（增加计数）
         */
        function switchMode() {
            if (currentMode === 'work') {
                // 工作完成，进入休息（不累计计数）
                const shouldLongRest = cycleCount % CONFIG.CYCLES_PER_LONG_REST === 0;

                if (shouldLongRest) {
                    currentMode = 'long-rest';
                    remainingSeconds = CONFIG.LONG_REST_TIME;
                    showNotification('长休息时间', `恭喜完成第${cycleCount}个番茄钟！享受15分钟的长休息吧。`, 4000);
                    if (CONFIG.notificationEnabled) {
                        sendDesktopNotification('🎉 长休息时间', `你已经完成了第${cycleCount}个番茄钟，现在开始15分钟的长休息！`);
                    }
                    if (CONFIG.audioEnabled) {
                        audioManager.playGentleNotification('work');
                    }
                } else {
                    currentMode = 'rest';
                    remainingSeconds = CONFIG.REST_TIME;
                    showNotification('休息时间', `完成第${cycleCount}个番茄钟！现在是5分钟休息时间。`, 3000);
                    if (CONFIG.notificationEnabled) {
                        sendDesktopNotification('☕ 休息时间', `完成第${cycleCount}个番茄钟！现在是5分钟休息时间。`);
                    }
                    if (CONFIG.audioEnabled) {
                        audioManager.playGentleNotification('work');
                    }
                }
            } else {
                // 休息完成，进入工作（累计计数）
                const completedCount = cycleCount;
                cycleCount++; // 完成一个完整的番茄钟周期（工作+休息），增加计数
                currentMode = 'work';
                remainingSeconds = CONFIG.WORK_TIME;
                showNotification('工作时间', `第${completedCount}个番茄钟完成！开始第${cycleCount}个番茄钟。`, 3000);
                if (CONFIG.notificationEnabled) {
                    sendDesktopNotification('🍅 工作时间', `第${completedCount}个番茄钟完成！开始第${cycleCount}个番茄钟。`);
                }
                if (CONFIG.audioEnabled) {
                    audioManager.playGentleNotification('rest');
                }

                // 更新今日统计
                incrementTodayStats();
            }

            // 保存数据到localStorage
            saveData();

            // 只在模式切换时更新激励内容
            updateDisplay(true); // 更新激励内容
        }

        function showModeSwitchNotification() {
            let notificationTitle, notificationMessage, audioType;

            if (currentMode === 'work') {
                // 工作时间到了，显示休息通知
                const shouldLongRest = cycleCount % CONFIG.CYCLES_PER_LONG_REST === 0;

                if (shouldLongRest) {
                    notificationTitle = '长休息时间';
                    notificationMessage = `恭喜完成第${cycleCount}个番茄钟！点击开始享受15分钟的长休息。`;
                    audioType = 'work';
                } else {
                    notificationTitle = '休息时间';
                    notificationMessage = `完成第${cycleCount}个番茄钟！点击开始享受5分钟休息时间。`;
                    audioType = 'work';
                }
            } else {
                // 休息时间到了，显示工作通知
                notificationTitle = '工作时间';
                notificationMessage = `休息结束！点击开始第${cycleCount + 1}个番茄钟。`;
                audioType = 'rest';
            }

            // 播放音频提醒
            if (CONFIG.audioEnabled) {
                audioManager.playGentleNotification(audioType);
            }

            // 发送桌面通知
            if (CONFIG.notificationEnabled) {
                sendDesktopNotification(notificationTitle, notificationMessage);
            }

            // 显示界面通知
            showNotification(notificationTitle, notificationMessage, 3000);
        }

        // ============ 数据持久化 ============
        /**
         * 数据缓存管理器
         * 减少localStorage访问，提升性能
         */
        const DataCache = {
            pomodoroData: null,
            todayData: null,
            historyData: null,

            /**
             * 获取缓存数据
             * @param {string} key - 缓存键名
             * @returns {Object|null} 缓存的数据
             */
            get(key) {
                if (this[key + 'Data'] === null) {
                    try {
                        const raw = localStorage.getItem(key);
                        this[key + 'Data'] = raw ? JSON.parse(raw) : null;
                    } catch (error) {
                        console.warn(`解析${key}数据失败:`, error);
                        this[key + 'Data'] = null;
                    }
                }
                return this[key + 'Data'];
            },

            /**
             * 设置缓存数据
             * @param {string} key - 缓存键名
             * @param {Object} value - 要缓存的数据
             */
            set(key, value) {
                this[key + 'Data'] = value;
                try {
                    localStorage.setItem(key, JSON.stringify(value));
                } catch (error) {
                    console.warn(`保存${key}数据失败:`, error);
                }
            },

            /**
             * 清除缓存数据
             * @param {string} key - 缓存键名
             */
            clear(key) {
                this[key + 'Data'] = null;
                try {
                    localStorage.removeItem(key);
                } catch (error) {
                    console.warn(`清除${key}数据失败:`, error);
                }
            }
        };

        function saveData() {
            try {
                const data = {
                    cycleCount: cycleCount,
                    lastUpdate: new Date().toISOString()
                };
                DataCache.set('pomodoroData', data);
            } catch (error) {
                console.warn('保存数据失败:', error);
                // 不影响主要功能，静默处理
            }
        }

        function loadData() {
            const savedData = DataCache.get('pomodoroData');
            if (savedData) {
                try {
                    cycleCount = savedData.cycleCount || 1; // 默认从1开始

                    // 检查是否是新的一天，如果是则重置计数
                    const lastUpdate = new Date(savedData.lastUpdate);
                    const now = new Date();
                    if (lastUpdate.toDateString() !== now.toDateString()) {
                        cycleCount = 1; // 新的一天从1开始
                        saveData();
                    }
                } catch (error) {
                    console.warn('读取保存数据失败，使用默认值:', error);
                    cycleCount = 1; // 默认从1开始
                    // 清除可能损坏的数据
                    DataCache.clear('pomodoroData');
                }
            }
        }

        // ============ 设置功能 ============
        function openSettings() {
            const modal = document.getElementById('settingsModal');
            modal.classList.add('show');

            // 加载当前设置到界面
            loadSettingsToUI();
            updateTodayStats();
        }

        function closeSettings() {
            const modal = document.getElementById('settingsModal');
            modal.classList.remove('show');
        }

        function loadSettingsToUI() {
            document.getElementById('workTimeInput').value = CONFIG.WORK_TIME / 60;
            document.getElementById('restTimeInput').value = CONFIG.REST_TIME / 60;
            document.getElementById('longRestTimeInput').value = CONFIG.LONG_REST_TIME / 60;
            document.getElementById('longRestIntervalInput').value = CONFIG.CYCLES_PER_LONG_REST;

            document.getElementById('audioEnabledInput').checked = CONFIG.audioEnabled;
            document.getElementById('notificationEnabledInput').checked = CONFIG.notificationEnabled;
            document.getElementById('volumeLevelInput').value = CONFIG.volumeLevel;

            document.getElementById('bgAnimationEnabledInput').checked = CONFIG.bgAnimationEnabled;
            document.getElementById('showCycleCountInput').checked = CONFIG.showCycleCount;
            document.getElementById('autoResetDailyInput').checked = CONFIG.autoResetDaily;
        }

        function saveSettings() {
            // 保存时间设置
            CONFIG.WORK_TIME = parseInt(document.getElementById('workTimeInput').value) * 60;
            CONFIG.REST_TIME = parseInt(document.getElementById('restTimeInput').value) * 60;
            CONFIG.LONG_REST_TIME = parseInt(document.getElementById('longRestTimeInput').value) * 60;
            CONFIG.CYCLES_PER_LONG_REST = parseInt(document.getElementById('longRestIntervalInput').value);

            // 保存提醒设置
            CONFIG.audioEnabled = document.getElementById('audioEnabledInput').checked;
            CONFIG.notificationEnabled = document.getElementById('notificationEnabledInput').checked;
            CONFIG.volumeLevel = document.getElementById('volumeLevelInput').value;

            // 保存显示设置
            CONFIG.bgAnimationEnabled = document.getElementById('bgAnimationEnabledInput').checked;
            CONFIG.showCycleCount = document.getElementById('showCycleCountInput').checked;
            CONFIG.autoResetDaily = document.getElementById('autoResetDailyInput').checked;

            // 应用显示设置
            applyDisplaySettings();

            // 保存到localStorage
            saveConfigData();

            // 如果当前没有运行，重置计时器以应用新设置
            if (!isRunning) {
                resetTimer();
            }

            closeSettings();
            showNotification('设置已保存', '您的设置已成功保存并应用', 2000);
        }

        function applyDisplaySettings() {
            // 应用背景动画设置
            if (CONFIG.bgAnimationEnabled) {
                document.body.style.setProperty('--animation-enabled', 'block');
            } else {
                document.body.style.setProperty('--animation-enabled', 'none');
            }

            // 应用循环计数显示设置
            const cycleCounter = document.querySelector('.cycle-counter');
            if (CONFIG.showCycleCount) {
                cycleCounter.style.display = 'block';
            } else {
                cycleCounter.style.display = 'none';
            }
        }

        function resetCycleCount() {
            if (confirm('确定要重置番茄钟计数吗？这将清除累计的番茄钟次数。')) {
                cycleCount = 1;
                saveData();
                updateDisplay(false);
                updateTodayStats();
                showNotification('计数已重置', '番茄钟计数已重置为1', 2000);
            }
        }

        function resetAllData() {
            if (confirm('确定要重置所有数据吗？这将清除所有设置和统计数据，且无法恢复。')) {
                // 重置循环计数
                cycleCount = 1;

                // 重置为默认配置
                CONFIG = {
                    WORK_TIME: 25 * 60,
                    REST_TIME: 5 * 60,
                    LONG_REST_TIME: 15 * 60,
                    CYCLES_PER_LONG_REST: 4,
                    audioEnabled: true,
                    notificationEnabled: true,
                    volumeLevel: 'normal',
                    bgAnimationEnabled: true,
                    showCycleCount: true,
                    autoResetDaily: true,
                    workMotivations: CONFIG.workMotivations,
                    restSuggestions: CONFIG.restSuggestions
                };

                // 清除所有localStorage数据
                localStorage.clear();

                // 应用设置
                applyDisplaySettings();

                // 重置计时器
                resetTimer();

                closeSettings();
                showNotification('数据已重置', '所有数据已重置为默认设置', 3000);
            }
        }

        function saveConfigData() {
            try {
                const configData = {
                    CONFIG: {
                        WORK_TIME: CONFIG.WORK_TIME,
                        REST_TIME: CONFIG.REST_TIME,
                        LONG_REST_TIME: CONFIG.LONG_REST_TIME,
                        CYCLES_PER_LONG_REST: CONFIG.CYCLES_PER_LONG_REST,
                        audioEnabled: CONFIG.audioEnabled,
                        notificationEnabled: CONFIG.notificationEnabled,
                        volumeLevel: CONFIG.volumeLevel,
                        bgAnimationEnabled: CONFIG.bgAnimationEnabled,
                        showCycleCount: CONFIG.showCycleCount,
                        autoResetDaily: CONFIG.autoResetDaily
                    },
                    lastUpdate: new Date().toISOString()
                };
                localStorage.setItem('pomodoroConfig', JSON.stringify(configData));
            } catch (error) {
                console.warn('保存配置失败:', error);
            }
        }

        function loadConfigData() {
            const savedConfig = localStorage.getItem('pomodoroConfig');
            if (savedConfig) {
                try {
                    const configData = JSON.parse(savedConfig);
                    Object.assign(CONFIG, configData.CONFIG);
                    console.log('配置已加载:', CONFIG);
                } catch (error) {
                    console.warn('加载配置失败，使用默认值:', error);
                }
            }
        }

        function updateTodayStats() {
            const today = new Date().toDateString();
            let todayCount = 0;

            const todayData = DataCache.get('pomodoroToday');
            if (todayData && todayData.date === today) {
                todayCount = todayData.count;
            }

            document.getElementById('todayStats').textContent = todayCount;
        }

        function incrementTodayStats() {
            const today = new Date().toDateString();

            try {
                let data = DataCache.get('pomodoroToday') || { date: today, count: 0 };
                if (data.date !== today) {
                    data = { date: today, count: 0 };
                }

                data.count++;
                DataCache.set('pomodoroToday', data);

                // 同时保存到历史记录
                saveToHistory(today, data.count);
            } catch (error) {
                console.warn('更新今日统计失败:', error);
            }
        }

        function saveToHistory(date, count) {
            try {
                let history = DataCache.get('pomodoroHistory') || {};
                history[date] = { count: count, date: date };
                DataCache.set('pomodoroHistory', history);
            } catch (error) {
                console.warn('保存历史记录失败:', error);
            }
        }

        function showHistory() {
            const modal = document.getElementById('historyModal');
            modal.classList.add('show');
            loadHistoryData();
        }

        function closeHistory() {
            const modal = document.getElementById('historyModal');
            modal.classList.remove('show');
        }

        function loadHistoryData() {
            try {
                const history = DataCache.get('pomodoroHistory') || {};

                // 计算统计数据
                const dates = Object.keys(history).sort().reverse();
                const totalCount = Object.values(history).reduce((sum, day) => sum + day.count, 0);
                const avgCount = dates.length > 0 ? Math.round(totalCount / dates.length) : 0;
                const streak = calculateStreak(history);

                // 更新统计显示
                document.getElementById('totalPomodoros').textContent = totalCount;
                document.getElementById('avgPomodoros').textContent = avgCount;
                document.getElementById('currentStreak').textContent = streak;

                // 显示历史列表
                const historyList = document.getElementById('historyList');

                if (dates.length === 0) {
                    historyList.innerHTML = '<div class="history-empty">暂无历史记录</div>';
                    return;
                }

                historyList.innerHTML = dates.slice(0, 30).map(date => {
                    const dateObj = new Date(date);
                    const formattedDate = dateObj.toLocaleDateString('zh-CN', {
                        month: '2-digit',
                        day: '2-digit'
                    });
                    const weekday = dateObj.toLocaleDateString('zh-CN', { weekday: 'short' });

                    return `
                        <div class="history-item">
                            <span class="history-date">${formattedDate} ${weekday}</span>
                            <span class="history-count">${history[date].count} 个番茄钟</span>
                        </div>
                    `;
                }).join('');

            } catch (error) {
                console.warn('加载历史记录失败:', error);
                document.getElementById('historyList').innerHTML = '<div class="history-empty">加载失败</div>';
            }
        }

        function calculateStreak(history) {
            const dates = Object.keys(history).sort();
            if (dates.length === 0) return 0;

            let streak = 1;
            const today = new Date();
            today.setHours(0, 0, 0, 0);

            // 检查今天是否有记录
            const todayStr = today.toDateString();
            if (!history[todayStr]) {
                // 如果今天没有记录，检查昨天
                today.setDate(today.getDate() - 1);
                const yesterdayStr = today.toDateString();
                if (!history[yesterdayStr]) {
                    return 0; // 今天和昨天都没有记录，连续天数为0
                }
            }

            // 计算连续天数
            for (let i = dates.length - 1; i > 0; i--) {
                const currentDate = new Date(dates[i]);
                const prevDate = new Date(dates[i - 1]);

                const diffDays = Math.floor((currentDate - prevDate) / (1000 * 60 * 60 * 24));

                if (diffDays === 1) {
                    streak++;
                } else {
                    break;
                }
            }

            return streak;
        }

        // ============ 初始化 ============
        function init() {
            // 加载配置和数据
            loadConfigData();
            loadData();
            updateDisplay();
            requestNotificationPermission();

            // 应用显示设置
            applyDisplaySettings();

            // 添加键盘快捷键
            document.addEventListener('keydown', (e) => {
                if (e.code === 'Space') {
                    e.preventDefault();
                    if (!isRunning) {
                        startTimer();
                    } else {
                        pauseTimer();
                    }
                } else if (e.code === 'KeyR' && (e.ctrlKey || e.metaKey)) {
                    e.preventDefault();
                    resetTimer();
                } else if (e.code === 'KeyS' && (e.ctrlKey || e.metaKey)) {
                    e.preventDefault();
                    skipTimer();
                } else if (e.code === 'Escape') {
                    // ESC键关闭设置
                    closeSettings();
                }
            });

            // 点击模态框背景关闭设置
            document.getElementById('settingsModal').addEventListener('click', (e) => {
                if (e.target === e.currentTarget) {
                    closeSettings();
                }
            });

            // 点击模态框背景关闭历史记录
            document.getElementById('historyModal').addEventListener('click', (e) => {
                if (e.target === e.currentTarget) {
                    closeHistory();
                }
            });

            // 页面关闭前保存数据
            window.addEventListener('beforeunload', () => {
            saveData();
            audioManager.cleanup();
        });

            console.log('番茄时钟应用已初始化');
            console.log('快捷键：空格键-开始/暂停，Ctrl+R-重置，Ctrl+S-跳过，ESC-关闭设置');
        }

        // 启动应用
        init();
    </script>
</body>
</html>